package com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet

import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import com.helasasa.maxfunds.lineofcredit.cashloan.R
import com.helasasa.maxfunds.lineofcredit.cashloan.databinding.ActivityGhanaProofWalletBinding
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.http.hitPoint
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.IProofGhanaWalletAddDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.IProofGhanaWalletBindChannelDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.IProofGhanaWalletDelDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.IProofGhanaWalletEmptyDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.IProofGhanaWalletSubmitDialogListener
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.ProofGhanaWalletAddDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.ProofGhanaWalletBindChannelDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.ProofGhanaWalletDelDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.ProofGhanaWalletEmptyDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.proof.wallet.subview.ProofGhanaWalletSubmitDialog
import com.helasasa.maxfunds.lineofcredit.cashloan.ghana.screen.subview.HotlineGhanaDialog
import org.json.JSONObject

class ProofGhanaWalletActivity : AppCompatActivity() {

    private lateinit var proofWalletViewModel: ProofGhanaWalletViewModel
    private lateinit var binding: ActivityGhanaProofWalletBinding
    private lateinit var adapter: ProofGhanaWalletPageAdapter
    private lateinit var delDialog: ProofGhanaWalletDelDialog
    private lateinit var emptyDialog: ProofGhanaWalletEmptyDialog
    private lateinit var addDialog: ProofGhanaWalletAddDialog
    private lateinit var bindChannelDialog: ProofGhanaWalletBindChannelDialog
    private lateinit var submitDialog: ProofGhanaWalletSubmitDialog

    @SuppressLint("NotifyDataSetChanged")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 数据模型
        proofWalletViewModel = ViewModelProvider(this)[ProofGhanaWalletViewModel::class.java]

        // 关联布局
        binding = ActivityGhanaProofWalletBinding.inflate(layoutInflater)
        setContentView(binding.root)

        // 用到的控件
        val hotline = binding.navbarRight
        val back = binding.navbarLeft
        val list = binding.list
        val addBg = binding.addBg
        val submit = binding.submit
        val loading = binding.loading

        // 初始化adapter
        adapter = ProofGhanaWalletPageAdapter(emptyList(), object : IProofGhanaWalletPageListener {
            override fun onClick(walletInfo: JSONObject, isDel: Boolean, isAdd: Boolean) {
                if (isDel) {
                    hitPoint("PROOF_WALLET_LIST_DEL", walletInfo.optString("id"))
                    proofWalletViewModel.askDeleteWallet(walletInfo)
                }
                if (isAdd) {
                    hitPoint("PROOF_WALLET_LIST_ADD")
                    proofWalletViewModel.askAddWallet()
                }
            }
        })
        list.layoutManager = LinearLayoutManager(this)
        list.adapter = adapter

        // 初始化del dialog
        delDialog = ProofGhanaWalletDelDialog(object : IProofGhanaWalletDelDialogListener {
            override fun onClick(walletId: String) {
                hitPoint("PROOF_WALLET_DIALOG_DEL", walletId)
                proofWalletViewModel.confirmDeleteWallet(walletId)
            }
        })

        // 初始化empty dialog
        emptyDialog = ProofGhanaWalletEmptyDialog(object : IProofGhanaWalletEmptyDialogListener {
            override fun onClick(type: Int) {
                if (0 == type) {
                    hitPoint("PROOF_WALLET_NO_MORE")
                    proofWalletViewModel.mainProcess()
                } else {
                    addDialog.showNow(supportFragmentManager, "walletInfo")
                }
            }
        })

        // 初始化add dialog
        addDialog = ProofGhanaWalletAddDialog(object : IProofGhanaWalletAddDialogListener {
            override fun onClick(type: String, mobile: String) {
                hitPoint("PROOF_WALLET_DIALOG_ADD")
                proofWalletViewModel.confirmAddWallet(type, mobile)
            }
        })

        // 初始化bind channel dialog
        bindChannelDialog =
            ProofGhanaWalletBindChannelDialog(object : IProofGhanaWalletBindChannelDialogListener {
                override fun onClick(channel: JSONObject?) {
                    if (channel != null) {
                        hitPoint("PROOF_WALLET_DIALOG_BIND_CHANNEL")
                        val type = channel.optString("value")
                        val mobile = channel.optString("mobile")
                        proofWalletViewModel.confirmAddWallet(type, mobile)
                    }
                }
            })

        // 初始化submit dialog
        submitDialog = ProofGhanaWalletSubmitDialog(object : IProofGhanaWalletSubmitDialogListener {
            override fun onClick(type: Int) {
                hitPoint("PROOF_WALLET_DIALOG_COMMIT")
                proofWalletViewModel.mainProcess()
            }
        })

        // 页面loading状态接口监听
        proofWalletViewModel.loadingResult.observe(this@ProofGhanaWalletActivity, Observer {
            val loadingResult = it ?: return@Observer

            if (loadingResult) {
                loading.visibility = View.VISIBLE
            } else {
                loading.visibility = View.GONE
            }
        })

        // 页面详情接口监听
        proofWalletViewModel.pageDetailResult.observe(this@ProofGhanaWalletActivity, Observer {
            val pageDetailResult = it ?: return@Observer

            loading.visibility = View.GONE
            // 提交按键是否可用
            if (pageDetailResult.bindCount != null) {
                if (pageDetailResult.bindCount == 0) {
                    submit.isEnabled = false
                    submit.setBackgroundResource(R.drawable.bg_blue_disable_cor_12dp)
                } else {
                    submit.isEnabled = true
                    submit.setBackgroundResource(R.drawable.bg_blue_cor_12dp)
                }
            } else {
                submit.isEnabled = false
                submit.setBackgroundResource(R.drawable.bg_blue_disable_cor_12dp)
            }

            if (pageDetailResult.error != null) {
                showMessage(pageDetailResult.error)
                // 渲染已绑列表
                if (pageDetailResult.items != null) {
                    adapter.dataList = pageDetailResult.items
                    adapter.notifyDataSetChanged()
                }
                return@Observer
            }

            // 增加钱包
            if (pageDetailResult.showAddDialog != null) {
                if (addDialog.isVisible) addDialog.dismissNow()
                addDialog.showNow(supportFragmentManager, "walletInfo")
                return@Observer
            }

            // 删除钱包
            if (pageDetailResult.showDelDialog != null) {
                delDialog.setWalletInfo(pageDetailResult.showDelDialog)
                delDialog.showNow(supportFragmentManager, "walletInfo")
                return@Observer
            }

            // 另外绑定channel钱包
            if (pageDetailResult.showBindChannelDialog != null) {
                if (bindChannelDialog.isVisible) bindChannelDialog.dismissNow()

                Handler(Looper.getMainLooper()).postDelayed({
                    bindChannelDialog.setWalletInfo(pageDetailResult.showBindChannelDialog)
                    bindChannelDialog.showNow(supportFragmentManager, "walletInfo")
                }, 800)
                return@Observer
            }

            // 显示钱包数不够弹框
            if (pageDetailResult.showEmptyDialog == true) {
                emptyDialog.showNow(supportFragmentManager, "walletInfo")
                return@Observer
            }

            if (pageDetailResult.showSubmitDialog == true) {
                submitDialog.setWalletList(pageDetailResult.items)
                submitDialog.showNow(supportFragmentManager, "walletInfo")
                return@Observer
            }

            // 渲染已绑列表
            if (pageDetailResult.items != null) {
                adapter.dataList = pageDetailResult.items
                adapter.notifyDataSetChanged()
            }
        })

        // 删除钱包接口监听
        proofWalletViewModel.walletDeleteResult.observe(this@ProofGhanaWalletActivity, Observer {
            val walletDeleteResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (walletDeleteResult.error != null) {
                showMessage(walletDeleteResult.error)
                return@Observer
            }
        })

        // 增加钱包接口监听
        proofWalletViewModel.walletAddResult.observe(this@ProofGhanaWalletActivity, Observer {
            val walletAddResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (walletAddResult.error != null) {
                showMessage(walletAddResult.error)
                return@Observer
            }

            addDialog.dismissNow()
            if (walletAddResult.channel != null) {
                proofWalletViewModel.askBindChannelWallet()
            }
        })

        // 流程接口监听
        proofWalletViewModel.mainProcessResult.observe(this@ProofGhanaWalletActivity, Observer {
            val mainProcessResult = it ?: return@Observer

            loading.visibility = View.GONE
            if (mainProcessResult.error != null) {
                showMessage(mainProcessResult.error)
            }

            if (mainProcessResult.success != null) {
                proofWalletViewModel.nextRouter(mainProcessResult.success)
            }
        })

        // 页面需要跳转监听
        proofWalletViewModel.nextRouterResult.observe(this@ProofGhanaWalletActivity, Observer {
            val nextRouterResult = it ?: return@Observer

            loading.visibility = View.GONE
            startNextActivity(nextRouterResult.nextPage)
        })

        // 点击客服
        hotline.setOnClickListener {
            // 客服弹框
            HotlineGhanaDialog().showNow(supportFragmentManager, "hotline")
            hitPoint("SHOW_HOTLINE")
        }

        // 点击返回
        back.setOnClickListener {
            finish()
        }

        // 点击添加卡
        addBg.setOnClickListener {
            hitPoint("PROOF_ADD_WALLET")
            proofWalletViewModel.askAddWallet()
        }

        // 点击提交
        submit.setOnClickListener {
            hitPoint("PROOF_WALLET_COMMIT")
            proofWalletViewModel.submitWallets()
        }

        // 查询页面详情
        submit.isEnabled = false
        proofWalletViewModel.pageDetail()
    }

    override fun onResume() {
        super.onResume()
        hitPoint(type = this::class.java.simpleName, isPageStart = true)
    }

    override fun onPause() {
        super.onPause()
        hitPoint(type = this::class.java.simpleName, isPageEnd = true)
    }

    fun startNextActivity(
        activity: Class<out AppCompatActivity>? = null,
        params: HashMap<String, String> = HashMap()
    ) {
        val nextActivity = activity ?: return
        try {
            val intent = Intent(this, nextActivity)
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_NEW_TASK)
            params.keys.forEach { gKey ->
                intent.putExtra(gKey, params[gKey])
            }
            startActivity(intent)
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}

interface IProofGhanaWalletPageListener {
    fun onClick(walletInfo: JSONObject, isDel: Boolean = false, isAdd: Boolean = false)
}

class ProofGhanaWalletPageAdapter(
    var dataList: List<JSONObject>,
    var onClick: IProofGhanaWalletPageListener? = null
) :
    RecyclerView.Adapter<ProofGhanaWalletPageAdapter.ViewHolder>() {

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int,
    ): ViewHolder {
        val view = LayoutInflater.from(parent.context)
            .inflate(R.layout.view_ghana_proof_wallet_activity_adapter, parent, false)
        return ViewHolder(view)
    }

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        private val title: TextView = view.findViewById(R.id.title)
        private val addBg: RelativeLayout = view.findViewById(R.id.addBg)
        private val walletBg: RelativeLayout = view.findViewById(R.id.walletBg)
        private val icon: ImageView = view.findViewById(R.id.icon)
        private val type: TextView = view.findViewById(R.id.type)
        private val account: TextView = view.findViewById(R.id.account)
        private val delBg: LinearLayout = view.findViewById(R.id.delBg)

        @SuppressLint("SetTextI18n")
        fun bindData(item: JSONObject, position: Int) {
            val isAdd = item.optBoolean("isAdd", false)
            if (isAdd) {
                addBg.visibility = View.VISIBLE
                walletBg.visibility = View.GONE

                delBg.setOnClickListener { }
                addBg.setOnClickListener {
                    onClick?.onClick(walletInfo = item, isAdd = true)
                }
            } else {
                addBg.visibility = View.GONE
                walletBg.visibility = View.VISIBLE

                title.text = "Portefeuille mobile ${position + 1}"
                type.text = item.optString("walletDesc")
                account.text = item.optString("walletMobile")

                val logo = item.optString("walletLogo")
                if (logo.isNotBlank()) {
                    icon.visibility = View.VISIBLE
                    Glide.with(icon).load(logo).into(icon)
                } else {
                    icon.visibility = View.GONE
                }

                addBg.setOnClickListener { }
                delBg.setOnClickListener {
                    onClick?.onClick(walletInfo = item, isDel = true)
                }
            }
        }
    }

    @SuppressLint("SetTextI18n")
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val data: JSONObject = dataList[position]
        holder.bindData(data, position)
    }

    override fun getItemCount(): Int {
        return dataList.size
    }
}

fun Context.showMessage(message: String) {
    Toast.makeText(applicationContext, message, Toast.LENGTH_SHORT).show()
}